﻿#!/bin/bash

set -e

IP=`hostname -I`
IP=`echo $IP`
PWD=/mnt/uos
SUBNET=192.168.225.0
broadcast=192.168.225.255
poolstart=192.168.225.10
poolstop=192.168.225.20
inet=ens33

if [ $UID != 0 ]
then
    echo "请以root身份运行此脚本!"
    exit 1
fi

#apt-get update

## 判断pxe文件夹是否存在，并检查是否已存在其他文件
if [ ! -d /tftpboot/pxelinux.cfg ]
then
	echo "pxe文件夹不完整，已新建..."
	mkdir -p /tftpboot/pxelinux.cfg
else
    echo 'pxe文件夹已存在'
fi

if [ `ls /tftpboot|grep -v 'pxelinux.cfg'|wc -c` -ne 0 ]
then
	echo "pxe文件夹不符合初始化环境，请删除/tftpboot文件夹，重新运行此脚本"
	exit 1
fi

#判断镜像文件是否存在并挂载
if [ ! -d /mnt/uos ]
then
    mkdir /mnt/uos
fi

mount /dev/sr0 /mnt/uos

#镜像复制
cp -a $PWD/isolinux/. /tftpboot
cp $PWD/live/vmlinuz /tftpboot
cp $PWD/live/initrd.lz /tftpboot

#复制pxelinux.0文件
cp ./pxelinux.0 /tftpboot

echo "
default vesamenu.c32
timeout 50
menu autoboot Starting Linux install in # second{,s}. Press any key to interrupt.
menu clear
menu title UOS20 
label UOS
  menu label Start UOS20 
  kernel vmlinuz
  append initrd=initrd.lz boot=live livecd-installer netboot=nfs nfsroot=$IP:$PWD locale=zh_CN.UTF-8
">/tftpboot/pxelinux.cfg/default

# 搭建DHCP服务器
if [ `dpkg -l|grep 'isc-dhcp-server'|wc -c` -eq 0 ]
then
	echo '正在安装DHCP服务器..'
	apt-get install isc-dhcp-server -y
else
	echo 'DHCP服务器已经安装'
fi

sed -i '18s/^/#/' /etc/default/isc-dhcp-server
sed -i '17s|"|"'"$inet"'|' /etc/default/isc-dhcp-server

## 设置子网和地址池
#read -p "输入DHCP服务器的网段: " SUBNET
#read -p "输入DHCP服务器的广播IP地址: " broadcast
#read -p "输入DHCP地址池起始IP地址" poolstart
#read -p "输入DHCP地址池结束IP地址" poolstop

echo "
allow booting;
allow bootp;
subnet $SUBNET netmask 255.255.255.0 { 
	range $poolstart $poolstop;   
	option routers $IP;  
	
	option broadcast-address $broadcast;  
	option domain-name-servers $IP; 
	default-lease-time 600;  
	max-lease-time 7200;  
	next-server $IP;  
	filename \"pxelinux.0\";   
}">>/etc/dhcp/dhcpd.conf

systemctl restart isc-dhcp-server

#搭建TFTP服务器
apt-get install tftp-hpa tftpd-hpa
echo '
TFTP_USERNAME="tftp"
TFTP_DIRECTORY="/tftpboot"
TFTP_ADDRESS="0.0.0.0:69" 
TFTP_OPTIONS="-l -c -s"
'>/etc/default/tftpd-hpa

chmod -R 777 /tftpboot
##重启服务
systemctl restart tftpd-hpa

#搭建NFS服务器
if [ `dpkg -l|grep 'nfs-kernel-server'|wc -c` -eq 0 ]
then
	echo '正在安装NFS服务器..'
	apt-get install nfs-kernel-server -y
else
	echo 'NFS服务器已经安装'
fi

echo "
/mnt/uos *(ro)">>/etc/exports
systemctl restart nfs-kernel-server
echo "PXE已完成部署！"
